<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增商品</el-button>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable />
          </el-form-item>
          <el-form-item label="商品分类" prop="cagegoryId">
            <el-select v-model="queryParams.cagegoryId" filterable clearable placeholder="请选择类型">
              <el-option v-for="(item) in allCategoryoneLevel" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>

    </el-row>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="编号" align="center" prop="id" width="50" />
      <el-table-column label="图片" align="left" prop="imgUrl">
        <template #default="scope">
          <div class="img-box">
            <el-image style="width: 100px; height: 50px" :src="scope.row.imgUrl" fit="cover" :preview-teleported="true">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" width="180" />
      <el-table-column label="描述" align="center" prop="desr" width="180" />
      <el-table-column label="零售价" align="center" prop="price" width="180" />
      <el-table-column label="促销价" align="center" prop="cuxiaoPrice" width="180" />
      <el-table-column label="会员价" align="center" prop="vipPrice" width="180" />
      <el-table-column label="分类" align="center" prop="categoryName" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link size="small" type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button link size="small" type="primary" icon="Plus" @click="addOrder(scope.row)">新增订单</el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.size"
      @pagination="getProductLists" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="dialogTitleText" v-model="open" width="600px" append-to-body @close="handleClose()">
      <el-form v-if="dialogTitleText == '编辑商品' ? false : true" ref="addFormRef" :model="form" :rules="rules"
        label-width="120px">
        <el-form-item label="商品名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述:" prop="desr">
          <el-input v-model="form.desr" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="商品零售价:" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品零售价"></el-input>
        </el-form-item>
        <el-form-item label="商品促销价:" prop="cuxiaoPrice">
          <el-input v-model="form.cuxiaoPrice" placeholder="请输入商品促销价"></el-input>
        </el-form-item>
        <el-form-item label="商品会员价:" prop="vipPrice">
          <el-input v-model="form.vipPrice" placeholder="请输入会员价"></el-input>
        </el-form-item>
        <el-form-item label="商品二级分类:" prop="cagegoryId">
          <el-select v-model="form.cagegoryId" filterable clearable placeholder="请选择类型">
            <el-option v-for="(item) in allCategoryoneLevel" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片:" prop="remark">
          <div class="flex-box">
            <UpFile ref="upFileRef" :file-list="fileList" multiple :limit="1" :size="1"
              accept=".jpg,.png,.gif,.jpeg,.webp"></UpFile>
          </div>
        </el-form-item>
      </el-form>
      <el-form v-else ref="editFormRef" :model="editForm" :rules="rules" label-width="120px">
        <el-form-item label="商品名称:" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述:" prop="desr">
          <el-input v-model="editForm.desr" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="商品零售价:" prop="price">
          <el-input v-model="editForm.price" placeholder="请输入商品零售价"></el-input>
        </el-form-item>
        <el-form-item label="商品促销价:" prop="cuxiaoPrice">
          <el-input v-model="editForm.cuxiaoPrice" placeholder="请输入促销价"></el-input>
        </el-form-item>
        <el-form-item label="商品会员价:" prop="vipPrice">
          <el-input v-model="editForm.vipPrice" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="商品二级分类:" prop="cagegoryId">
          <el-select v-model="editForm.cagegoryId" filterable clearable placeholder="请选择类型">
            <el-option v-for="(item) in allCategoryoneLevel" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片:" prop="remark">
          <div class="flex-box">
            <UpFile ref="upFileRef" :file-list="fileList" multiple :limit="1" :size="1"
              accept=".jpg,.png,.gif,.jpeg,.webp"></UpFile>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-loading="loading">
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm()">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增订单 -->
    <el-dialog title="新增订单" v-model="open2" width="600px" append-to-body @close="handleClose2()">
      <el-form ref="addFormRef" :model="form" :rules="rules"
        label-width="120px">
        <el-form-item label="单价:" prop="name">
          <el-input v-model="addOrderForm.price" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="数量:" prop="desr">
          <el-input v-model="addOrderForm.num" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商:" prop="price">
          <el-select v-model="addOrderForm.providerId" filterable clearable placeholder="请选择类型">
              <el-option v-for="item in providerList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="地址:" prop="cuxiaoPrice">
          <el-input v-model="addOrderForm.address" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
     
      <template #footer>
        <div class="dialog-footer" v-loading="loading">
          <el-button @click="open2 = false">取 消</el-button>
          <el-button type="primary" @click="submitForm2()">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import UpFile from "@/components/upFile/index.vue";
import { addFile, upFileReq, getImg, delFile } from "@/api/components/index.js";
import { getProductList, addProduct,editProduct,delProduct,addProductOrder } from "@/api/product/index.js"
import { getAllCategoryList } from '@/api/productCategory/index.js' 
import { getProviderList } from "@/api/product/index.js"
import { reactive } from "vue";

const { proxy } = getCurrentInstance();
const list = ref([]);
const open = ref(false);
const open2 = ref(false);

const loading = ref(false);
const fileList = ref([]);
const upFileRef = ref(null);
const dialogTitleText = ref('')
const total = ref(0);


let moreArr = reactive([
  { value: 1, label: '生活衣装' },
  { value: 2, label: '体育用品' },
]);

let fileId;
const data = reactive({
  form: {},
  editForm: {
    name: '',
    desr: '',
    price: '',
    cuxiaoPrice: '',
    vipPrice: '',
    cagegoryId: '',
    id: ''
  },
  addOrderForm:{
    price:'',
    num:'',
    providerId:'',
    address:'',
    productId:'',
    productName:''
  },
  queryParams: {
    page: 1,
    size: 10,
  },
  queryParams2: {
    page: 1,
    size: 1000,
  },
  allCategoryoneLevel: [],

  providerList:[]
});
const { allCategoryoneLevel,addOrderForm,providerList,editForm, form, queryParams,queryParams2 } = toRefs(data);
function handleClose2(){
  open2.value = false
}
function submitForm2(){
  addProductOrder(addOrderForm.value).then(res => {
    if(res.code == 1){
      proxy.$modal.msgSuccess("新增成功");
      open2.value = false
    }
  })
}

function getProviderList2(){
  getProviderList(queryParams2.value).then(res => {
    if(res.code == 1){
      let arr = []
      res.data.map(ele => {
        arr.push({label:ele.name,value:ele.id})
      })
      providerList.value = arr
      console.log('66666', providerList.value)
    }
  })
}
function addOrder(row){
  open2.value = true
  getProviderList2()
  addOrderForm.value.productId = row.id
  addOrderForm.value.productName = row.name
  
  

}
function handleAdd() {
  open.value = true;
  getAllCategoryData()
  dialogTitleText.value = '新增商品'
  fileId = undefined;
  nextTick(() => {
    upFileRef.value.clearFiles();
  })
}
async function handleUpdate(row) {
  open.value = true;
  fileId = row.id;
  nextTick(() => {
    fileList.value = imgEvent(row);
  })
  dialogTitleText.value = '编辑商品'
  editForm.value.name = row.name
  editForm.value.desr = row.desr
  editForm.value.price = row.price
  editForm.value.cuxiaoPrice = row.cuxiaoPrice
  editForm.value.vipPrice = row.vipPrice
  editForm.value.cagegoryId = Number(row.cagegoryId)
  editForm.value.id = row.id
  editForm.value.imgUrl = row.imgUrl
  getProductLists();



}
async function submitForm() {
  if (dialogTitleText.value !== '编辑商品') {
    await proxy.$refs["addFormRef"].validate();
    const imgRes = upFileRef.value.getFileRes();
    if (imgRes.length === 0) return proxy.$modal.msgError("请上传商品图片");
    try {
      loading.value = true;
      const data = { ...form.value, imgUrl: imgRes[0].url };
      !form.value.id && await addProduct({ ...data });
      // form.value.id&&await upUser(data);
      proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
      open.value = false;
      getProductLists();
    } finally {
      loading.value = false;
    }
  } else {
    const imgRes = upFileRef.value.getFileRes();
    try {
      loading.value = true;
      const imgRes = upFileRef.value.getFileRes();

      if (imgRes.length === 0) {
      }else{
        editForm.value.imgUrl =  imgRes[0].url
      }
      const data = { ...editForm.value};
      !form.value.id && await editProduct({ ...data });
      // form.value.id&&await upUser(data);
      proxy.$modal.msgSuccess(editForm.value.id ? "修改成功" : "新增成功");
      open.value = false;
      getProductLists();
    } finally {
      loading.value = false;
    }

  }

}
async function handleDelete(row) {
  await proxy.$modal.confirm("确认删除当前商品数据吗？");
  await delProduct({ id: row.id });
  proxy.$modal.msgSuccess("删除成功");
  getProductLists();

}
function formatCategory(categoryId) {
  let foundLabel = null; // 初始化一个变量来存储找到的 label
  for (let i = 0; i < allCategoryoneLevel.value.length; i++) {
    const ele = allCategoryoneLevel.value[i];
    if (Number(categoryId) == ele.value) {
      foundLabel = ele.label; // 当找到匹配的项时，设置 foundLabel
      break; // 跳出循环
    }
  }
  return foundLabel; // 返回找到的 label，如果没有找到则返回 null
}
async function getProductLists() {
  try {
    loading.value = true;
    await getAllCategoryData()
    const { data, total: totalAll } = await getProductList(queryParams.value);
    total.value = totalAll;
    list.value = data;
    list.value.forEach(ele => {
      ele.price = ele.price
      ele.vipPrice = ele.vipPrice
      ele.cuxiaoPrice = ele.cuxiaoPrice
      ele.categoryName = formatCategory(ele.cagegoryId)

    })
  } finally {
    loading.value = false;
  }
}
function handleQuery() {
  queryParams.value.page = 1;
  getProductLists();
}
function imgEvent(row) {
  try {
    return JSON.parse(row.val)
  } catch (e) {
    return []
  }
}
function handleClose(){
  form.value = {}
}
async function getAllCategoryData() {
  try {
    // loading.value = true;
    const { data } = await getAllCategoryList(queryParams2.value);
    allCategoryoneLevel.value = []

    data.forEach(ele => {
      if (ele.levelId == 2) {
        allCategoryoneLevel.value.push(ele)
      }
    })
    allCategoryoneLevel.value.forEach(ele => {
      ele.label = ele.name
      ele.value = ele.id
    })
    console.log('所有二级分类', allCategoryoneLevel.value)


  } finally {
    // loading.value = false;
  }
}
// getImgApi();

getProductLists()
</script>

<style scoped lang="scss">
.flex-box {
  text-align: center;
}

.img-box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: auto;

  >div {
    margin: 0 5px;
  }
}
</style>